package c_6_3_6;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 死锁
 *
 * @author lfg
 * @version 1.0
 */
public class DeadLock {
    /**
     * 狗狗，先持有猫咪的锁，再去获取狗狗的锁
     * 猫咪，先持有狗狗的锁，再去获取猫咪的锁
     * 造成死锁
     */
    public static ReentrantLock dog = new ReentrantLock();
    public static ReentrantLock cat = new ReentrantLock();

    public static class DogThread extends Thread {

        @Override
        public void run() {
            try {
                //持有猫咪锁
                cat.lockInterruptibly();

                Thread.sleep(1000);

                //获取狗狗锁
                dog.lockInterruptibly();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (cat.isHeldByCurrentThread()) {
                    cat.unlock();
                }
                if (dog.isHeldByCurrentThread()) {
                    dog.unlock();
                }
            }
        }
    }

    public static class CatThread extends Thread {
        @Override
        public void run() {
            try {
                //持有狗狗锁
                dog.lockInterruptibly();

                Thread.sleep(1000);

                //获取猫咪锁
                cat.lockInterruptibly();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (cat.isHeldByCurrentThread()) {
                    cat.unlock();
                }
                if (dog.isHeldByCurrentThread()) {
                    dog.unlock();
                }
            }
        }
    }

}